package com.ts.api.module.distribute.controller;

import com.gitee.apanlh.util.net.addr.IpUtils;
import com.gitee.apanlh.util.thread.LockExecutor;
import com.gitee.apanlh.web.util.ServletUtils;
import com.ts.api.module.distribute.entity.DistributeLinkPO;
import com.ts.api.module.distribute.entity.bo.DistributeLinkBO;
import com.ts.api.module.distribute.service.DistributeService;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *  分配代理链接
 */
@Slf4j
@Controller
@RequestMapping("/distribute")
public class DistributeController {

    @Autowired
    private DistributeService distributeService;

    /**
     *  动态分配链接渠道
     *
     *  @param response
     */
    @GetMapping("/redirect/{uniqueCode}")
    public void redirect(@PathVariable String uniqueCode, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String ipAddr = IpUtils.getIpAddr(request);
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getHeader("User-Agent"));

        //  获取子链接列表
        List<DistributeLinkPO> list = distributeService.list(uniqueCode);
        if (CollectionUtils.isEmpty(list)) {
            response.setStatus(302);
            response.sendRedirect("https://100");
            return ;
        }

        DistributeLinkBO linkBO = LockExecutor.executeWriteLockFormReadWrite("get distribute link", () -> {
            //  获取业务子链接列表
            List<DistributeLinkBO> listBO = distributeService.checkLinkAndModify(list);
            //  获取子链接
            return distributeService.getDistributeLink(list, listBO);
        });

        distributeService.insertGroupVisitor(ipAddr, userAgent, linkBO);
        if (linkBO.getUrl() != null) {
            distributeService.insertLinkVisitor(ipAddr, userAgent, linkBO);
        }

        if (linkBO.getUrl() == null) {
            response.setStatus(302);
            response.sendRedirect("https://none.cn");
            log.info("无子链接跳转");
            return ;
        }

        response.setStatus(302);
        response.sendRedirect(linkBO.getUrl());
    }

}
